package pit.com.ordermobilesystem.fragment;
import java.io.UnsupportedEncodingException;
import org.json.JSONArray;
import org.json.JSONObject;
import pit.com.ordermobilesystem.AddCategoryActivity;
import pit.com.ordermobilesystem.BaseFragment;
import pit.com.ordermobilesystem.R;
import pit.com.ordermobilesystem.ShopActivity;
import pit.com.ordermobilesystem.BaseFragment.TypeLoadingMore;
import pit.com.ordermobilesystem.adapter.CategoryAdapter;
import pit.com.ordermobilesystem.fragment.ShopFragment.LoadingShop;
import pit.com.ordermobilesystem.http.HttpApiException;
import pit.com.ordermobilesystem.http.OrderSystemHttpService;
import pit.com.ordermobilesystem.provider.OrderMobileProvider;
import pit.com.ordermobilesystem.sharepreference.OrderSharePreference;
import android.app.Activity;
import android.content.ContentValues;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.Configuration;
import android.database.ContentObserver;
import android.database.Cursor;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v4.widget.SwipeRefreshLayout.OnRefreshListener;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ImageView;

import com.capricorn.ArcLayout;
import com.capricorn.ArcMenu;
import com.etsy.android.grid.StaggeredGridView;

public class CategoryFragment extends BaseFragment{
	  View rootView;
	  int ACTION_ADD_CATEGORY=1;
	  StaggeredGridView gridView;
	SwipeRefreshLayout swipeLayout;	  
	  int ITEM_DRAWABLES[]={R.drawable.ic_arc_plus,R.drawable.ic_arc_delete,R.drawable.ic_arc_edit};
	    @Override
	    public void onCreate(Bundle savedInstanceState) {
	        super.onCreate(savedInstanceState);

	    }

	    @Override
	    public View onCreateView(LayoutInflater inflater, ViewGroup container,
	            Bundle savedInstanceState) {
	        rootView = inflater.inflate(R.layout.fragment_category, container, false);
	        ArcMenu menu = (ArcMenu) rootView.findViewById(R.id.arc_menu);
	        gridView = (StaggeredGridView) rootView.findViewById(R.id.grid_view);
	        ArcLayout arcLayout= new ArcLayout(getActivity());
	        //arcLayout.setChildSize(50);
	        arcLayout.setArc(0.0f, 360.0f); 

	        if(!OrderSharePreference.getUser(getActivity()).equals("")){
	        	
	        }else{
	        	menu.setVisibility(View.GONE);
	        }


	        final int itemCount = ITEM_DRAWABLES.length;
	        for (int i = 0; i < itemCount; i++) {
	            ImageView item = new ImageView(getActivity());
	            item.setImageResource(ITEM_DRAWABLES[i]);

	            final int position = i;
	            menu.addItem(item, new OnClickListener() {

	                @Override
	                public void onClick(View v) {
	                    if(position==0){
					Intent newIntent = new Intent( getActivity(), AddCategoryActivity.class );
					getActivity().startActivityForResult(newIntent,  ACTION_ADD_CATEGORY); 		                	    
	                    }else if(position==1){
	                	    
	                    }else{
//	                	    	CategoryAdapter adapter=(CategoryAdapter) viewFlow.getAdapter();
//	                	    	
//	                	    	JSONObject category;
//					try {
//						category = adapter.getCurrentItem();
//						Intent newIntent = new Intent( getActivity(), AddCategoryActivity.class );
//						newIntent.putExtra("data", category.toString());
//						getActivity().startActivityForResult(newIntent,  ACTION_ADD_CATEGORY); 					
//					} catch (JSONException e) {
//						// TODO Auto-generated catch block
//						e.printStackTrace();
//					}

	                    }
	                }
	            });// Add a menu item
	        }
	        
			swipeLayout = (SwipeRefreshLayout) rootView.findViewById(R.id.swipe_container);
	        swipeLayout.setOnRefreshListener(new OnRefreshListener() {
				
				@Override
				public void onRefresh() {
			        new LoadingCategory(TypeLoadingMore.PULL_TO_REFRESH).execute();	
					
				}
			});
	        swipeLayout.setColorScheme(android.R.color.holo_blue_bright, 
	                android.R.color.holo_green_light, 
	                android.R.color.holo_orange_light, 
	                android.R.color.holo_red_light);	
	        getActivity().getContentResolver().delete(OrderMobileProvider.CATEGORY_CONTENT_URI, null, null);
	        new LoadingCategory(TypeLoadingMore.LOADING_FIRST).execute();	
	        return rootView;
	    }

	@Override
	public void onConfigurationChanged(Configuration newConfig) {
		super.onConfigurationChanged(newConfig);

	}
	    

	ContentObserver contentObserver = new ContentObserver(new Handler()) {

		@Override
		public void onChange(boolean selfChange) {
			super.onChange(selfChange);
			synchronized (this) {
				Cursor data = getActivity().getContentResolver().query(
						OrderMobileProvider.CATEGORY_CONTENT_URI, null, null, null,
						null);
				if (data != null) {
		
						if (gridView.getAdapter() == null) {
							CategoryAdapter adapter = new CategoryAdapter(getActivity(), data,getParentFragment());
							gridView.setAdapter(adapter);
						} else {
							CategoryAdapter adapter=(CategoryAdapter) gridView.getAdapter();
							adapter.changeCursor(data);

						}	

				}				
			}
				

		}
	};	
	
	
	@Override
	public void onPause() {
		super.onPause();
		getActivity().getContentResolver().unregisterContentObserver(contentObserver);		
	}

	@Override
	public void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		contentObserver.onChange(true);
		getActivity().getContentResolver().registerContentObserver(OrderMobileProvider.CATEGORY_CONTENT_URI, true, contentObserver);

	}
	

	class LoadingCategory extends AsyncTask<String, Void, Void> {

		TypeLoadingMore typeLoading;
		Exception exception;
		int response_code;
		
		
		public LoadingCategory(TypeLoadingMore typeLoading) {
			super();
			this.typeLoading = typeLoading;
		}
		protected void onPreExecute() {
			if(typeLoading==TypeLoadingMore.LOADING_FIRST){
				showProgressDialog(new DialogInterface.OnCancelListener() {
					
					@Override
					public void onCancel(DialogInterface dialog) {
						LoadingCategory.this.cancel(true);
						dialog.dismiss();
						swipeLayout.setRefreshing(false);
					}


				});
			}

		}

		protected Void doInBackground(final String... args) {
			OrderSystemHttpService httpService=new OrderSystemHttpService(OrderSharePreference.getHost(getActivity()),OrderSharePreference.getPort(getActivity()));
			try {
				ShopActivity activity=(ShopActivity) getActivity();
				JSONObject result=httpService.requestToService(OrderSystemHttpService.URL_GET_LIST_CATEGORY, "{\"sale_id\":"+activity.getData().getInt("id")+"}");
				//JSONObject result=httpService.requestToService(OrderSystemHttpService.URL_SUBMIT_ORDER, "{\"name_order\":\"order mobile\",\"name_customer\":\"thong nguyen\",\"mobile_customer\":\"0908184981\",\"date_order\":\"1345646546\",\"discount\":8000,\"sum_price\":5000,\"description\":\"\",\"is_finish\":1}");
				if(result.getString("status").equals("ok")){		
					JSONArray arrayCategory=result.getJSONObject("data").getJSONArray("categories");
					ContentValues[] listValues=new ContentValues[arrayCategory.length()];					
					for(int i=0;i<arrayCategory.length();i++){
						listValues[i]=OrderMobileProvider.getContentValues(getActivity(),arrayCategory.getJSONObject(i));
					}
					//Insert into database
					getActivity().getContentResolver().bulkInsert(OrderMobileProvider.CATEGORY_CONTENT_URI, listValues);				
					getActivity().getContentResolver().notifyChange(OrderMobileProvider.CATEGORY_CONTENT_URI, null);
				}else{
					exception=new Exception(result.getString("error"));
				}

			} catch (UnsupportedEncodingException e) {
				// TODO Auto-generated catch block
				exception=e;
			} catch (HttpApiException e) {
				// TODO Auto-generated catch block
				exception=e;
			} catch (Exception e) {
				// TODO Auto-generated catch block
				exception=e;
			}
			return null;
		}

		protected void onPostExecute(final Void unused) {

				hideProgressDialog();
				swipeLayout.setRefreshing(false);
			
			if(exception!=null){
				showAlert("",exception.getMessage());
			}
			
		}

	}


	@Override
	public void onActivityResult(int requestCode, int resultCode,
			Intent data) {
		if(resultCode==Activity.RESULT_OK){
			if(requestCode==ACTION_ADD_CATEGORY){
				new LoadingCategory(TypeLoadingMore.LOADING_FIRST).execute();
			}
		}
		super.onActivityResult(requestCode, resultCode, data);
	}	


}
